const {
  formatTime
} = require("../../../utils/util");

// pages/home/detail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailInfo: {},
    picList: [],
    bottomDesc: '',
    statusMap: {
      0: '报名中',
      1: '已截止',
      2: '已截止'
    },
    attendList: [
      {
        nickName: '昵称不可用',
        avatarUrl: '',
        attendDate: '2022/04/01 20:00'
      },
      {
        nickName: '大象',
        avatarUrl: '',
        attendDate: '2022/04/01 20:00'
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const id = options?.id || 1;
    this.requestDetailInfo(id);
  },

  requestDetailInfo: function (id) {
    let token = getApp().globalData.token || '';

    const that = this;
    wx.cloud.callContainer({
      config: {
        env: "prod-9gno6bd407ac56da"
      },
      path: `/api/activity/${id}`,
      header: {
        "X-WX-SERVICE": "springboot-kd4g",
        "token": token
      },
      method: "GET",
      data: {},
      success(res) {
        let detail = res?.data?.data || {};
        if (detail.startTime) {
          detail.startTime = formatTime(new Date(detail.startTime))
        }
        if (detail.updateTime) {
          detail.updateTime = formatTime(new Date(detail.updateTime))
        }

        let bottomDesc = ''
        if (detail.joined) {
          bottomDesc = `已报名, 当前共${detail.currentUsers}人参与该活动`
        } else if (detail.status == 0) {
          bottomDesc = `已报名人数：${detail.currentUsers}`
        } else {
          bottomDesc = `活动已成团`
        }

        that.setData({
          detailInfo: detail,
          picList: detail?.pics || [],
          bottomDesc
        })
      }
    })
  },

  updateUserInfo: function (value) {
    let token = getApp().globalData.token;
    wx.cloud.callContainer({
      config: {
        env: "prod-9gno6bd407ac56da"
      },
      path: "api/user/update",
      header: {
        "X-WX-SERVICE": "springboot-kd4g",
        "token": token
      },
      method: "POST",
      data: {
        nickName: value.nickName || '',
        avatarUrl: value.avatarUrl || ''
      },
      success(res) {
        if (res?.data?.code == 0) {
          console.log('用户信息更新成功')
        }
      }
    })
  },

  onJoin: function () {
    const that = this
    // 首先判断用户是否授权
    try {
      let nickName = getApp().globalData.nickName;
      if (nickName) {
        that.joinActivity();
      } else {
        wx.getUserProfile({
          desc: '获取用户信息',
          success: (res) => {
            getApp().globalData.nickName = res?.userInfo?.nickName
            getApp().globalData.avatarUrl = res?.userInfo?.avatarUrl

            that.updateUserInfo(res?.userInfo);
            that.joinActivity();
          },
          fail: (res) => {
            wx.showToast({
              title: '请先授权',
              icon: 'error'
            })
          }
        })
      }
    } catch (e) {

    }
  },

  joinActivity: function () {
    const that = this;

    const max = that.data?.detailInfo?.maxUsers || 0;
    const current = that.data?.detailInfo?.currentUsers || 0;
    if (current + 1 > max) {
      wx.showToast({
        title: '报名人数已满',
        icon: 'error'
      })
      return
    }

    let token = getApp().globalData.token || '';

    if (token) {
      that.callJoin(token);
    } else {
      // 登陆
      wx.login({
        success: res => {
          if (res.code) {
            // 请求接口获取token，保存
            wx.cloud.callContainer({
              config: {
                env: "prod-9gno6bd407ac56da"
              },
              path: "/api/user/login",
              header: {
                "X-WX-SERVICE": "springboot-kd4g"
              },
              method: "POST",
              data: {
                jsCode: res.code,
                nickName: '',
                avatarUrl: ''
              },
              success(res) {
                if (res?.data?.code == 0) {
                  let accessToken = res?.data?.data?.accessToken || '';
                  getApp().globalData.token = accessToken;

                  that.callJoin(accessToken);
                }
              }
            })
          }
        }
      })
    }
  },

  callJoin: function (token) {
    const that = this;
    wx.cloud.callContainer({
      config: {
        env: "prod-9gno6bd407ac56da"
      },
      path: `/api/activity/join`,
      header: {
        "X-WX-SERVICE": "springboot-kd4g",
        "token": token
      },
      method: "POST",
      data: {
        activityId: that.data.detailInfo.id
      },
      success(res) {
        if (res && res.data && res.data.code == 0) {
          wx.showToast({
            title: '报名成功',
          })
          that.requestDetailInfo(that?.data?.detailInfo?.id)
        } else {
          wx.showToast({
            title: res?.data?.errorMsg || '报名失败',
            icon: 'error'
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})